<template>
  <div class="app-container">
    <div
      v-show="
        !(detailInfo.visible || modifyInfo.visible) && !detailListInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :queryMoreJson="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clearType="clearType"
          :slipSelectRequest="slipSelectRequest"
        >
        </NewPageFilter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-delete>
            <el-button :disabled="!canDelete" @click="remove()">删除</el-button>
          </template>
          <template v-slot:filter-outStock>
            <el-button :disabled="!canOutStock" @click="outStock()"
              >出库</el-button
            >
          </template>
          <template v-slot:filter-break>
            <el-button :disabled="!canBreak" @click="breakUp()">撤回</el-button>
          </template>
          <template v-slot:filter-stockReturn>
            <el-button :disabled="!canReturnStock" @click="breakUpStock()"
              >撤回出库</el-button
            >
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>

      <div class="flex_full_item">
        <!-- 表格 -->
        <TableContainer
          :refresh="tableInfo.refresh"
          :init-curpage="tableInfo.initCurpage"
          v-model:data="tableInfo.data"
          :api="tableInfo.api"
          v-model:query="filterInfo.query"
          :field-list="tableInfo.fieldList"
          :handle="tableInfo.handle"
          :row-class-name="tableRowClassName"
          @sortChange="sortChange"
          @handleEvent="handleEvent"
        >
          <template v-slot:col-orderNo="scope">
            <!--<span-->
            <!--class="slip-edit"-->
            <!--v-if="$permission('purchReturn:detail')"-->
            <!--@click="showDetail(scope.row)"-->
            <!--&gt;{{scope.row.orderNo}}</span>-->
            <span
              class="slip-edit"
              v-if="$permission('purchReturn:details')"
              @click="showDetail(scope.row)"
              >{{ scope.row.orderNo }}</span
            >
            <span v-else>{{ scope.row.orderNo || '-' }}</span>
          </template>
          <template v-slot:col-updateTime="scope">
            <span v-if="scope.row.status === 'complete'">{{
              scope.row.updateTime
            }}</span>
            <span v-else>-</span>
          </template>
        </TableContainer>
      </div>
    </div>
    <!-- 新增或修改 -->
    <purch-return-modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :purchReturnId="modifyInfo.purchReturnId"
      :purchAccording="modifyInfo.purchAccording"
      @returnModify="returnModify"
    />
    <purch-return-detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :purchReturnId="detailInfo.purchReturnId"
      @returnBack="getList"
    />
    <!-- 输入入库单号弹窗 -->
    <PageDialog
      v-if="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
      @reset="close"
    >
      <!-- form -->
      <PageForm
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="formInfo.ref"
        :data="formInfo.data"
        :field-list="formInfo.fieldList"
        :rules="formInfo.rules"
        :label-width="formInfo.labelWidth"
      />
    </PageDialog>
    <SetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :searchList="filterInfo.searchList"
      :fieldList="tableInfo.fieldList"
      :customizeUserVO="filterInfo.query.customizeUserVO"
      :groupLevelShow="false"
      @callback="setPreferenceCallback"
    />
    <AdvancedSearch
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:formData="advancedSearchInfo.data"
      :fieldList="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></detailList>
    <page-dialog
      v-if="pageDialogInfo.visible"
      :title="pageDialogInfo.title"
      v-model:visible="pageDialogInfo.visible"
      :width="pageDialogInfo.width"
      :bt-loading="pageDialogInfo.btLoading"
      :bt-list="pageDialogInfo.btList"
      @reset="close"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="pageFormInfo.ref"
        :data="pageFormInfo.data"
        :field-list="pageFormInfo.fieldList"
        :label-width="pageFormInfo.labelWidth"
      />
    </page-dialog>
  </div>
</template>

<script setup name="purchReturn">
import PurchReturnDetail from './detail'
import purchReturnModify from './modify'
import DetailList from './detailList'
import {
  getPurchReturnPage,
  purchReturnSubmit,
  purchReturnExport,
  purchReturnRetract,
  purchReturnInvalid,
  purchReturnDelete,
  purchReturnBreakUpExport,
  purchReturnUpdateReceive,
  purchCancelDownShelf,
} from '@/api/purch'
import { getSupplierAll } from '@/api/core'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
const { proxy } = getCurrentInstance()
const route = useRoute()
const listTypeInfo = ref({
  supplierList: [],
})
const updateTime = ref([])
const createTime = ref([])
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {
      deptAuth: {
        asTbName: 'purch_return',
        columnName: 'dept_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'deptAuth',
      },
      depotAuth: {
        asTbName: 'purch_return',
        columnName: 'depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'depotAuth',
      },
      supplierAuth: {
        asTbName: 'purch_return',
        columnName: 'supplier_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'supplierAuth',
      },
    },
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('purchReturn:add'),
    },
    {
      type: 'slot',
      value: 'delete',
      show: proxy.$permission('purchReturn:delete'),
    },
    {
      type: 'slot',
      value: 'outStock',
      show: proxy.$permission('purchReturn:export'),
    },
    {
      type: 'slot',
      value: 'break',
      show: proxy.$permission('purchReturn:retract'),
    },
    {
      type: 'slot',
      value: 'stockReturn',
      show: proxy.$permission('purchReturn:breakUpExport'),
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('purchReturn:update'),
        ifRender: function (row) {
          return row.status === 1 || row.status === 5
        },
      },
      {
        label: '提交',
        event: submit,
        show: proxy.$permission('purchReturn:submit'),
        ifRender: function (row) {
          return row.status === 1 || row.status === 5
        },
      },
      {
        label: '撤回',
        event: breakUp,
        show: proxy.$permission('purchReturn:retract'),
        ifRender: function (row) {
          return row.status === 3
        },
      },
      {
        label: '出库',
        event: outStock,
        show: proxy.$permission('purchReturn:export'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '作废',
        event: invalidUp,
        show: proxy.$permission('purchReturn:invalid'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '取消拣货',
        event: doCancelDown,
        show: proxy.$permission('purchReturn:cancelDown'),
        ifRender: function (row) {
          return row.status === 9
        },
      },
      {
        label: '撤回出库',
        event: breakUpStock,
        show: proxy.$permission('purchReturn:breakUpExport'),
        ifRender: function (row) {
          return row.status === 4
        },
      },
      {
        label: '删除',
        event: remove,
        show: proxy.$permission('purchReturn:delete'),
        ifRender: function (row) {
          return row.status === 1 || row.status === 5
        },
      },
      {
        label: "关联入库单号",
        event: inputReceivingOn,
        show: proxy.$permission("purchReturn:relatedReceivingNo"),
        ifRender: function(row) {
          return row.status === 7 && row.returnType === 2;
        }
      }
    ],
  },
})
//明细相关
const detailInfo = ref({
  visible: false,
  purchReturnId: '',
})
//新增或更新相关
const modifyInfo = ref({
  visible: false,
  title: '',
  purchReturnId: '',
  purchAccording: '',
})
const formInfo = ref({
  ref: null,
  data: {
    receivingOrderNo: '',
  },
  fieldList: [
    {
      label: '入库单号',
      value: 'receivingOrderNo',
      type: 'textarea',
      maxlength: 200,
      placeholder: '请输入关联的入库单号',
    },
  ],
})
const dialogInfo = ref({
  title: '入库单号',
  visible: false,
  type: '',
  width: '400px',
  row: {},
  btLoading: false,
  btList: [
    { label: '关闭', type: '', icon: '', event: close, show: true },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      event: save,
      saveLoading: false,
      show: true,
    },
  ],
})
const pageDialogInfo = ref({
  title: '选择采购依据',
  visible: false,
  type: '',
  width: '400px',
  row: {},
  btLoading: false,
  btList: [
    {
      label: '关闭',
      type: '',
      icon: '',
      event: closeDialog,
      show: true,
    },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      event: saveDialog,
      saveLoading: false,
      show: true,
    },
  ],
})
const pageFormInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '采购依据',
      value: 'purch_according',
      type: 'select-model',
      code: 'purch_according',
    },
  ],
})
const detailListInfo = ref({
  visible: false,
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const clearType = ref(true)
const slipSelectRequest = ref(true)
watch(
  () => route,
  (val) => {
    const params = val.params
    if (params && params.purchApplicationId && val.name === 'purchReturn') {
      detailInfo.value.visible = false
      modifyInfo.value.visible = false
    }
  },
  { immediate: true }
)
watch(
  () => filterInfo.value.query.updateTimeGreater,
  (val) => {
    if (!val) {
      updateTime.value = null
    }
  }
)
watch(
  () => filterInfo.value.query.createTimeGreater,
  (val) => {
    if (!val) {
      createTime.value = null
    }
  }
)
const canDelete = computed(() => {
  return (
    tableInfo.value.selections.length !== 0 &&
    tableInfo.value.selections.filter((item) => item.status !== 1).length === 0
  )
})
const canSubmit = computed(() => {
  return (
    tableInfo.value.selections.length !== 0 &&
    tableInfo.value.selections.filter((item) => item.status !== 1).length === 0
  )
})
const canBreak = computed(() => {
  return (
    tableInfo.value.selections.length !== 0 &&
    tableInfo.value.selections.filter((item) => item.status !== 3).length === 0
  )
})
const canOutStock = computed(() => {
  return (
    tableInfo.value.selections.length !== 0 &&
    tableInfo.value.selections.filter((item) => item.status !== 2).length === 0
  )
})
const canReturnStock = computed(() => {
  return (
    tableInfo.value.selections.length !== 0 &&
    tableInfo.value.selections.filter((item) => item.status !== 4).length === 0
  )
})

const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})
let stopWatch = function () {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'purchReturn' && el.url === val.url) {
                detailInfo.value.visible = false
                modifyInfo.value.visible = false
                detailInfo.value.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  proxy.$nextTick(() => {
                    detailInfo.value.visible = true
                    detailInfo.value.orderNo = val.orderNo
                    detailInfo.value.purchReturnId = val.orderId
                    sessionStorage.setItem('storeRowId', val.orderId)
                    console.log(detailInfo.value, 11111111)
                  })
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})
onDeactivated(() => {
  stopWatch()
})

function closeDialog() {
  pageDialogInfo.value.visible = false
  pageFormInfo.value.data = {}
}
function saveDialog() {
  if (pageFormInfo.value.data.purch_according) {
    modifyInfo.value.title = '新增采购退货单'
    modifyInfo.value.purchReturnId = ''
    modifyInfo.value.purchAccording = pageFormInfo.value.data.purch_according
    closeDialog()
    proxy.$nextTick(() => {
      modifyInfo.value.visible = true
    })
  } else {
    proxy.$message.warning('请选择采购依据')
  }
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
function updateTimeChange(val) {
  if (val && val.length) {
    filterInfo.value.query.updateTimeGreater = val[0]
    filterInfo.value.query.updateTimeLess = val[1]
  } else {
    filterInfo.value.query.updateTimeGreater = ''
    filterInfo.value.query.updateTimeLess = ''
  }
}
function createTimeChange(val) {
  if (val && val.length) {
    filterInfo.value.query.createTimeGreater = val[0]
    filterInfo.value.query.createTimeLess = val[1]
  } else {
    filterInfo.value.query.createTimeGreater = ''
    filterInfo.value.query.createTimeLess = ''
  }
}
function returnModify() {
  if (modifyInfo.value.purchReturnId) {
    getList()
  } else {
    search()
  }
}
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.value.query.queryMap = {}
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
}
// 获取列表
async function getList() {
  tableInfo.value.refresh = Math.random()
}

// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
function initSupplierSelect() {
  const params = {
    supplierAuth: 'supplierId',
  }
  getSupplierAll(params).then((resp) => {
    if (resp && resp.success) {
      listTypeInfo.value.supplierList = resp.data.map((item) => {
        return {
          key: item.supplierName,
          value: item.supplierId,
        }
      })
    }
  })
}
// 创建
function create() {
  if (
    proxy.$store.state.permission.systemConfig.purch_according != '1' &&
    proxy.$store.state.permission.systemConfig.purch_according != '2'
  ) {
    pageDialogInfo.value.visible = true
  } else {
    modifyInfo.value.visible = true
    modifyInfo.value.title = '新增采购退货单'
    modifyInfo.value.purchReturnId = ''
    modifyInfo.value.purchAccording = ''
  }
}
// 编辑
function update(data) {
  sessionStorage.setItem('storeRowId', data.id)
  modifyInfo.value.visible = true
  modifyInfo.value.title = '修改采购退货单'
  // 显示信息
  modifyInfo.value.purchReturnId = data.id
  modifyInfo.value.purchAccording = ''
}
//删除
function remove(row) {
  let data = []
  if (row) {
    data.push(row.id)
  } else {
    data = tableInfo.value.selections.map((item) => item.id)
  }
  proxy.$handleAPI('delete', purchReturnDelete, data).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//展示明细
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.value.purchReturnId = row.id
  detailInfo.value.visible = true
}
//提交
function submit(row = undefined) {
  const ids = getIds(row)
  purchReturnSubmit(ids).then((resp) => {
    if (resp.success) {
      tableInfo.value.refresh = Math.random()
    }
  })
}
function getIds(row = undefined) {
  let ids = []
  if (row) {
    ids.push(row.id)
  } else {
    ids = tableInfo.value.selections.map((row) => row.id)
  }
  return ids
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function outStock(row) {
  const ids = getIds(row)
  purchReturnExport(ids).then((resp) => {
    if (resp.success) {
      tableInfo.value.refresh = Math.random()
    }
  })
}
function breakUp(row) {
  const ids = getIds(row)
  purchReturnRetract(ids).then((resp) => {
    if (resp.success) {
      tableInfo.value.refresh = Math.random()
    }
  })
}
function invalidUp(row) {
  const ids = getIds(row)
  purchReturnInvalid(ids).then((resp) => {
    if (resp.success) {
      tableInfo.value.refresh = Math.random()
    }
  })
}
function doCancelDown(row = undefined) {
  proxy
    .$confirm('确认取消拣货吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      purchCancelDownShelf({ id: row.id }).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
      })
    })
    .catch(() => {})
}
function breakUpStock(row) {
  const ids = getIds(row)
  purchReturnBreakUpExport(ids).then((resp) => {
    if (resp.success) {
      tableInfo.value.refresh = Math.random()
    }
  })
}
function inputReceivingOn(row) {
  dialogInfo.value.visible = true
  dialogInfo.value.row = row
  formInfo.value.data.receivingOrderNo=row.receivingOrderNo
}
function close() {
  dialogInfo.value.visible = false
  formInfo.value.data.receivingOrderNo = ''
  dialogInfo.value.row = {}
}
function save() {
  let params = {
    ...dialogInfo.value.row,
    receivingOrderNo: formInfo.value.data.receivingOrderNo,
  }
  purchReturnUpdateReceive(params).then((res) => {
    if (res && res.success) {
      getList()
      close()
    }
    dialogInfo.value.visible = false
  })
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey: 'purchpurchReturnList-com.slip.spd.entity.vo.purch.PurchReturnVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.value.api = getPurchReturnPage
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}

let obj = {
  typeValue: {
    label: '类型',
    value: 'typeValue',
    asValue: 'type',
    componentType: 'select-model',
    code: 'purch_return_type',
    show: false,
    hidden: true,
  },
  statusValue: {
    label: '状态',
    value: 'statusValue',
    asValue: 'status',
    componentType: 'select-model',
    code: 'purch_return_status',
    show: false,
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.value.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()
</script>

<style scoped></style>
